import React, { Component } from 'react'
import {Redirect} from 'react-router-dom'
import './login.css'
import { Form, Input, Button, Checkbox, message } from 'antd';
import Logo from '../../assets/images/logo.png'
import apis from '../../apis/apis'
import memoryUtils from '../../utils/memoryUtils'

const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 6,
    span: 18,
  },
};

export default class Login extends Component {
  onFinish = async (values) => {
    // console.log(this.props.history.push('/home'));
    const {account, password} = values;
    const {data} = await apis.users.login({account, password})
    console.log(data);
    if(data.code) {
      localStorage.token = data.data.token
      localStorage.user = JSON.stringify(data.data.userInfo)
      memoryUtils.user = data.data.userInfo
      this.props.history.push('/home')
    }else {
      this.error();
    }

  };
  onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  validatorPass = (rule, value, callback) => {
    if(!value) {
      callback("密码不能为空");
    }else {
      //验证通过
      callback();
    }
  }
  error = () => {
    message.error('用户名或密码错误');
  };
  componentDidMount() {
    
  }
  render() {
    if(memoryUtils.user.account){ console.log(memoryUtils.user); return <Redirect to="/home"/> }
    return (
      <div className="login">
        <div className="login-wrap">
          <div className="logowrap">
            <img src={Logo} width="200px" alt="" className="logoimg"/>
          </div>
          <Form
            {...layout}
            name="basic"
            initialValues={{
              remember: true,
            }}
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
          >
          <Form.Item
            label="用户名："
            name="account"
            rules={[
              {
                required: true,
                message: '用户名不能为空',
              },
            ]}
          >
          <Input />
          </Form.Item>

          <Form.Item
            label="密码："
            name="password"
            rules={[
              {validator: this.validatorPass}
            ]}
          >
          <Input.Password />
          </Form.Item>

          <Form.Item {...tailLayout} name="remember" valuePropName="checked">
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
        </div>
        
      </div>
    )
  }
}
